# -*- coding: utf-8 -*-
import logging
import os
from datetime import datetime

class DailyRotatingFileHandler(logging.FileHandler):
    """按日期滚动日志文件"""
    
    def __init__(self, base_dir='logs', prefix='app'):
        self.base_dir = base_dir
        self.prefix = prefix
        os.makedirs(self.base_dir, exist_ok=True)
        
        # 获取当前日志文件名
        filename = self._get_filename()
        super().__init__(filename, encoding='utf-8')
        
    def _get_filename(self):
        date_str = datetime.now().strftime('%Y-%m-%d')
        return os.path.join(self.base_dir, f'{self.prefix}_{date_str}.log')
        
    def emit(self, record):
        # 检查是否需要切换日志文件
        current_filename = self._get_filename()
        if self.baseFilename != current_filename:
            self.close()
            self.baseFilename = current_filename
            self.stream = self._open()
            
        super().emit(record)

def setup_logger():
    """配置日志系统"""
    logger = logging.getLogger('school_score_system')
    logger.setLevel(logging.INFO)
    
    # 控制台输出
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    
    # 文件输出（按天滚动）
    file_handler = DailyRotatingFileHandler()
    
    # 统一日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    console_handler.setFormatter(formatter)
    file_handler.setFormatter(formatter)
    
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    
    return logger

# 全局日志对象
logger = setup_logger()